package org.yiqixue.accounts.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.yiqixue.accounts.dto.TransactionDto;
import org.yiqixue.accounts.entity.Accounts;
import org.yiqixue.accounts.entity.Transaction;
import org.yiqixue.accounts.mapper.TransactionMapper;
import org.yiqixue.accounts.repository.AccountsRepository;
import org.yiqixue.accounts.repository.CustomerRepository;
import org.yiqixue.accounts.repository.TransactionRepository;
import org.yiqixue.accounts.service.ITransactionService;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TransactionService implements ITransactionService {

    private TransactionRepository transactionRepository;
    private AccountsRepository accountsRepository;
    private CustomerRepository customerRepository;

    /**
     * 根据手机号和交易类型查询当日的所有交易
     * @param mobileNumber 手机号
     * @param type 交易类型
     * @param transactionDate 交易日期
     * @return 符合条件的交易记录列表
     */
    @Override
    public List<TransactionDto> getTransactionsByMobileNumberAndType(String mobileNumber, String type, Date transactionDate) {
        var customer = customerRepository.findByMobileNumber(mobileNumber)
                .orElseThrow(() -> new RuntimeException("未找到该手机号对应的客户"));
        var accounts = accountsRepository.findByCustomerId(customer.getCustomerId())
                .orElseThrow(() -> new RuntimeException("未找到该客户对应的账户"));
        var transactions = transactionRepository.findByAccountNumberAndTypeAndTransactionDate(
                accounts.getAccountNumber(), type, transactionDate);
        return transactions.stream()
                .map(TransactionMapper::mapToTransactionDto)
                .collect(Collectors.toList());
    }

    /**
     * 插入一条交易记录
     * @param transactionDto 交易信息
     */
    @Override
    public void insertTransaction(TransactionDto transactionDto) {
        var transaction = TransactionMapper.mapToTransaction(transactionDto, new Transaction());
        transactionRepository.save(transaction);
    }
}